﻿

using IotContract.Grpcs;
using IotServer.Configs;
using IotServer.Grpcs;
using IotServer.Services;
using IotServerService;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.Options;
using ProtoBuf.Grpc.Server;
using ProtoBuf.Meta;
using System.Net;
using System.Reflection;
using XT.Common.Config;
using XT.Common.Interfaces;
using XT.Common.Models;
using XT.Common.Models.WinService;
using XT.Common.Services;
using XT.Sql;
using XT.Sql.Extensions;
using XT.Sql.Models;
using XT.WinService;

var builder = WebApplication.CreateBuilder(args);

// 添加Log4net日志
ShareService.ConfigureLog4net();

builder.Services.AddSingleton(implementationInstance: new AppSettings(builder.Environment.IsDevelopment()));




ShareService.AddWinService(builder.Services);


// 配置
builder.Services.AddSingleton<IApiConfig, ApiConfig>();
// window服务启动服务
builder.Services.AddSingleton<IWindowService, ServerWinService>();


// 添加grpc服务
builder.Services.AddCodeFirstGrpc((options) =>
{
    options.MaxReceiveMessageSize = int.MaxValue;
    options.MaxSendMessageSize = int.MaxValue;
});





// 添加服务端逻辑
builder.Services.RegisterServerService();
// 扩展程序
builder.Services.RegisterServerProcess();



builder.WebHost.UseKestrel(options =>
{
    options.Listen(IPAddress.Any, 20000, o =>
    {
        o.Protocols = HttpProtocols.Http2; // with this line or not - both works fine

    });
});

// builder.WebHost.ConfigureKestrel(options =>
// {
//     // Setup a HTTP/2 endpoint without TLS.
//     options.ListenLocalhost(5000, o => o.Protocols =
//         HttpProtocols.Http2);
// });

var app = builder.Build();

// 添加具体的grpc服务
app.AddGrpcService();

string ext = string.Empty;
var location = AppDomain.CurrentDomain.BaseDirectory.Replace("\\", "-");
var locations = location.Split("-").ToList();
locations.RemoveAt(locations.Count - 1);


if (locations.Count < 4)
{
    ext = location;
}
else
{
    ext = string.Join("-", locations.TakeLast(3));
}



ShareService.RunWinService(app.Services, new ServiceInfo
{
    Description = "IotServer服务",
    DisplayName = "IotServer-"+ext,
    Name = "IotServer-"+ext
});

await app.RunAsync();



/// <summary>
/// Map Grpc服务
/// </summary>
public static class MapService
{
    public static void AddGrpcService(this WebApplication builder)
    {
        builder.MapGrpcService<ConnectGrpcService>();
        builder.MapGrpcService< RemoteGrpcService>();
    }

   
}
